using System;
using System.Collections.Generic;
using System.Data.SQLite;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;

namespace Sec_scan漏洞扫描系统.Sec_Service
{
    /// <summary>
    /// 指纹扫描服务
    /// </summary>
    public class Sec_FingerScan_Service
    {
        private static bool RemoteCertificateValidate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error)
        {
            return true;
        }
        /// <summary>
        /// 指纹扫描服务
        /// </summary>
        /// <param name="finger"></param>
        /// <returns></returns>
        public static string FingerScan(string finger)
        {
            Sec_Api.Sec_FingerScan_Service_Api.ExpOptions = new StringBuilder();//实例化错误信息输出接口
            string url = Sec_Api.Sec_FingerScan_Service_Api.Url;//获取漏洞扫描地址
            //string url = "https://211.71.235.147"; 存在的
            string loop = Sec_Api.Sec_AllAPI.Sqlclient(Sec_Api.Sec_LoopScan_Service_Api.P1);//链接漏洞数据库
            SQLiteConnection connection = new SQLiteConnection(loop);
            try
            {
                connection.Open();
                if(connection.State == System.Data.ConnectionState.Open)
                {
                    string sql = Sec_Api.Sec_AllAPI.FingerInfos(Sec_Api.Sec_FingerScan_Service_Api.F1);//查询指纹数据库 所有指纹数据
                    SQLiteCommand command = new SQLiteCommand(sql, connection);
                    using(SQLiteDataReader dr = command.ExecuteReader(System.Data.CommandBehavior.CloseConnection))
                    {
                        while (dr.Read())
                        {
                            string fid = dr["ID"].ToString();
                            string fname = dr["fingename"].ToString();//指纹名称
                            string fpath = dr["fingepath"].ToString();//指纹名称
                            //指纹路径解密
                            string key_1 = Sec_Api.Sec_DesThreDesApi.DesKeyInfo(Sec_Api.Sec_DesThreDesApi.D1);//密文一
                            string key_2 = Sec_Api.Sec_DesThreDesApi.DeskeyInfoOne(Sec_Api.Sec_DesThreDesApi.D1);//密文二
                            string key_3 = Sec_Api.Sec_DesThreDesApi.DeskeyInfoTwo(Sec_Api.Sec_DesThreDesApi.D1);//密文三
                            string payload = Sec_Config.Sec_DesThreDes.Decrypt(fpath, key_1, key_2, key_3);
                            string base1 = Sec_Config.Sec_Base64Code.Gobase64(payload);

                            string fkey = dr["fingekey"].ToString();//指纹特征
                            string keys = Sec_Config.Sec_DesThreDes.Decrypt(fkey, key_1, key_2, key_3);
                            string base2 = Sec_Config.Sec_Base64Code.Gobase64(keys);

                            string fip = dr["fingeip"].ToString();//指纹校验地址
                            string fversion = dr["systemversion"].ToString();//指纹系统版本
                            string ftype = dr["systemtype"].ToString();//指纹系统类型
                            try
                            {
                                ServicePointManager.ServerCertificateValidationCallback += RemoteCertificateValidate;
                                HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(url + base1);//URL加指纹路径
                                httpReq.Method = "GET";//获取请求方式
                                httpReq.Accept = "*/*";
                                httpReq.ServicePoint.Expect100Continue = false;//加快载入速度
                                httpReq.ServicePoint.UseNagleAlgorithm = false;//禁止nagle算法加快载入速度
                                httpReq.AllowWriteStreamBuffering = false;//禁止缓冲加快载入速度
                                //下面这行可能会造成解析的代码乱码
                                //httpReq.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");//定义gzip压缩页面支持
                                httpReq.ContentType = "application/x-www-form-urlencoded";//定义文档类型及编码
                                httpReq.AllowAutoRedirect = false;//禁止自动跳转
                                httpReq.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36";
                                //httpReq.Timeout = 2000;//请求超时
                                httpReq.KeepAlive = true;//启用长连接
                                httpReq.ServicePoint.ConnectionLimit = int.MaxValue;//定义最大连接数
                                HttpWebResponse response = (HttpWebResponse)httpReq.GetResponse();
                                Stream receiveStream = response.GetResponseStream();
                                StreamReader readStream = new StreamReader(receiveStream, Encoding.GetEncoding("UTF-8"));
                                string html = readStream.ReadToEnd();
                                if(System.Text.RegularExpressions.Regex.IsMatch(html, base2))
                                {
                                    //如果相同的情况下
                                    Console.WriteLine("存在的URL地址是：" + url + "关键特征是：" + base2);
                                }
                                else
                                {
                                    //不相同的情况下
                                    Console.WriteLine("不相同：" + url, base2);
                                }
                            }
                            catch(Exception ex)
                            {
                                //Console.WriteLine(ex);
                                Sec_Api.Sec_FingerScan_Service_Api.ExpOptions.Append(ex.ToString());
                            }
                        }
                    }
                }
            }
            catch(Exception ex)
            {
                string exp = ex.ToString();
                Sec_Api.Sec_FingerScan_Service_Api.ExpOptions.Append(exp);
            }
            return finger;
        }
    }
}
